package org.deng.vertx.common.util.file;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author 邓力宾
 * @date 2020-08-07 11:53
 * @desc
 */
public class FileUtils {
    private FileUtils(){}

    /**
     * 使用nio复制文件
     * @param inputStream
     * @param outputStream
     */
    public static  void copyFileByNio(FileInputStream inputStream, FileOutputStream outputStream) throws IOException {

        FileChannel inChannel = inputStream.getChannel();

        FileChannel outChannel = outputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int read = 0;
        //int total = 0;
        while((read = inChannel.read(byteBuffer)) > 0){ //达到末尾返回-1
           // System.out.println("读取后,position:"+byteBuffer.position()+",limit:"+byteBuffer.limit()); //position:1024,limit:1024
            byteBuffer.flip();
          //  System.out.println("读取后归零,position:"+byteBuffer.position()+",limit:"+byteBuffer.limit());//position:0,limit:1024

            outChannel.write(byteBuffer);
            //System.out.println("写入后,position:"+byteBuffer.position()+",limit:"+byteBuffer.limit()); //position:1024,limit:1024
            byteBuffer.flip();
          //  System.out.println("写入后归零,position:"+byteBuffer.position()+",limit:"+byteBuffer.limit());//position:0,limit:1024
            //total+= read;

        }
        inChannel.close();
        inputStream.close();
        outChannel.close();
        outputStream.close();
    }

    /**
     * 复制文件
     * @param inputStream
     * @param outputStream
     */
    public static  void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException {
        BufferedInputStream bufi = new BufferedInputStream(inputStream);
        BufferedOutputStream bufo = new BufferedOutputStream(outputStream);
        copyFileByBuffer(bufi, bufo);
        bufi.close();
        bufo.close();
    }
    /**
     * 复制文件 不会关闭流，需要调用者自己关闭
     * @param inputStream
     * @param outputStream
     */
    public static  void copyFileNotCloseStream(InputStream inputStream, OutputStream outputStream) throws IOException {
        BufferedInputStream bufi = new BufferedInputStream(inputStream);
        BufferedOutputStream bufo = new BufferedOutputStream(outputStream);
        copyFileByBuffer(bufi, bufo);

    }
    private static void copyFileByBuffer(BufferedInputStream bufi, BufferedOutputStream bufo) throws IOException {
        byte[] buffer= new byte[1024];
        int len;
        while((len = bufi.read(buffer)) > 0){
            bufo.write(buffer, 0, len);
        }
        bufo.flush();
    }
}
